/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yheriatovych.reductor.example;

import com.yheriatovych.reductor.example.model.Note;
import com.yheriatovych.reductor.example.util.NumCalcUtil;
import com.yheriatovych.reductor.example.util.ReboundHelper;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Checkbox;
import ohos.agp.components.RecycleItemProvider;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.multimodalinput.event.TouchEvent;
import rx.functions.Action1;
import java.util.List;

/**
 * list item provider
 *
 * @since 2021-05-06
 */
public class SampleItemProvider extends RecycleItemProvider {
    private static final int NUM2 = 2;
    private static final int OFFSET = 8;
    private static final int STROKEWIDTH = 6;
    private static final int RADIUSSMALL = 12;
    private static final int RADIUSBIG = 20;
    private static final int MINTIME = 200;
    private static final int MINDISTANCE = 100;
    private List<Note> mNotes;
    private AbilitySlice mSlice;
    private final Action1<Note> onClickListener;
    private final Action1<Note> onTouchListener;

    private ReboundHelper mReboundHelper;

    /**
     * 构造器
     *
     * @param notes
     * @param slice
     * @param onClickListener
     * @param onTouchListener
     */
    public SampleItemProvider(List<Note> notes, AbilitySlice slice, Action1<Note> onClickListener,
                              Action1<Note> onTouchListener) {
        this.mNotes = notes;
        this.mSlice = slice;
        this.onClickListener = onClickListener;
        this.onTouchListener = onTouchListener;

        mReboundHelper = new ReboundHelper(component -> {
            if (component.getTranslationX() != 0) {
                onTouchListener.call((Note) component.getTag());
                notifyDataChanged();
            }
        });
    }

    @Override
    public int getCount() {
        return mNotes.size();
    }

    @Override
    public Object getItem(int position) {
        return mNotes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        Component cpt = convertComponent;
        if (cpt == null) {
            cpt = LayoutScatter.getInstance(mSlice).parse(ResourceTable.Layout_item_sample, null, false);
        }
        final Note note = mNotes.get(position);
        Checkbox checkbox = (Checkbox) cpt.findComponentById(ResourceTable.Id_item_index);
        checkbox.setText(note.getNote());
        checkbox.setChecked(note.isChecked());
        checkbox.setClickable(false);
        cpt.setClickedListener(view -> {
            onClickListener.call(note);
            checkbox.invalidate();
        });
        cpt.setTranslationX(0);
        cpt.setTag(note);
        Component finalCpt = cpt;
        cpt.setTouchEventListener(new Component.TouchEventListener() {
            long time = 0L;
            int lastX;
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
                    lastX = (int) touchEvent.getPointerScreenPosition(0).getX();
                    time = System.currentTimeMillis();
                }
                if (touchEvent.getAction() == TouchEvent.POINT_MOVE) {
                    finalCpt.setTranslationX(NumCalcUtil.subtract(touchEvent.getPointerScreenPosition(0).getX(),
                            lastX));
                }
                onItemTouch(touchEvent, finalCpt, note, time, lastX);
                return true;
            }
        });
        return cpt;
    }

    private void onItemTouch(TouchEvent touchEvent, Component component, Note note, long time, int startX) {
        switch (touchEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_UP:
                float offsetX = component.getTranslationX();
                if (System.currentTimeMillis() - time < MINTIME
                        && Math.abs(
                        NumCalcUtil.subtract(touchEvent.getPointerScreenPosition(0).getX(), startX))
                        > MINDISTANCE) {
                    float toX = component.getWidth() * (offsetX / Math.abs(offsetX));
                    mReboundHelper.reboundX(component, toX);
                } else {
                    float halfWidth = NumCalcUtil.divide(component.getWidth(), NUM2);
                    if (offsetX <= halfWidth && offsetX >= -halfWidth) {
                        mReboundHelper.reboundX(component, 0);
                    }
                    else if (offsetX > 0) {
                        mReboundHelper.reboundX(component, component.getWidth());
                    } else {
                        mReboundHelper.reboundX(component, -component.getWidth());
                    }
                }
                break;
            case TouchEvent.CANCEL: mReboundHelper.reboundX(component, 0); break;
            default:
        }
    }

    public void setNotes(List<Note> notes) {
        this.mNotes = notes;
    }
}
